package com.novel.resource.minio.autoConfigurer;

import com.novel.resource.minio.config.MinioConfig;
import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * minio 配置类
 *
 * @author novel
 * @date 2020/1/3
 */
@Configuration
@ConditionalOnClass({MinioClient.class})
@EnableConfigurationProperties(MinioConfig.class)
@Slf4j
@AllArgsConstructor
public class MinioAutoConfiguration {
    private final MinioConfig minioConfig;

    @Bean
    @ConditionalOnMissingBean(MinioClient.class)
    @ConditionalOnProperty(prefix = MinioConfig.MINIO_PREFIX, name = "url")
    public MinioClient minioClient() throws Exception {
        log.info("MinioClient 初始化...");
        MinioClient minioClient = new MinioClient(minioConfig.getUrl(), minioConfig.getPort(), minioConfig.getAccessKey(), minioConfig.getSecretKey(), minioConfig.isSecure());
        //检测资源桶是否存在，不存在子创建
        if (!minioClient.bucketExists(minioConfig.getBucketName())) {
            minioClient.makeBucket(minioConfig.getBucketName());
        }
        return minioClient;
    }
}
